2326. Spiral Matrix IV
難度: 中等偏易
給定一鏈結串列head
,及二整數m
n
。
回傳m
* n
大小的矩陣,從左上角開始,按照順時鐘螺旋(右下左上右)的順序填入head
中的值,若填不完則剩於格子的都填入-1。
如上述題意,可拆解為子問題:
每一圈如下圖
→→ ... →⭣
↑→ ⭣
. .
. .
. .
←← ... ←←
簡單粗暴地刻出來~
class Solution {
public:
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
vector<vector<int>> res(m, vector<int>(n, -1));
// Current indexes
int i = 0, j = 0;
int round = 0;
ListNode* curr = head;
while(curr)
{
int rd = n - 1 - round * 2; // Right distance
// Go right
while(curr && rd > 0)
{
res[i][j] = curr->val;
// Update indexes
j++;
rd--;
curr = curr->next;
}
int dd = m - 1 - round * 2; // Down distance
// Go down
while(curr && dd)
{
res[i][j] = curr->val;
// Update indexes
i++;
dd--;
curr = curr->next;
}
int ld = n - 1 - round * 2; // Left distance
// Go down
while(curr && ld)
{
res[i][j] = curr->val;
// Update indexes
j--;
ld--;
curr = curr->next;
}
int ud = m - 1 - round * 2 - 1; // Up distance
// Go down
while(curr && ud)
{
res[i][j] = curr->val;
// Update indexes
i--;
ud--;
curr = curr->next;
}
// Go right and go next round
if(curr)
{
res[i][j] = curr->val;
j++;
curr = curr->next;
}
round++;
}
return res;
}
};
若head
長度為N,矩陣大小m * n
時間複雜度: O(mn + N),初始化m * n矩陣,接著遍歷head
空間複雜度: O(1),除了output無須額外空間
Time Submitted | Status | Runtime | Memory | Language |
---|---|---|---|---|
09/09/2024 20:49 | Accepted | 159 ms | 130.7 MB | cpp |
Accepted
50/50 cases passed (159 ms)
Your runtime beats 73.51 % of cpp submissions
Your memory usage beats 17.37 % of cpp submissions (130.7 MB)